package com.lw.common.ext

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.lw.common.utils.ByteArrayToBase64Adapter

/**
 * json转object
 */
inline fun <reified T> String.jsonToObject(gson: Gson = defaultGsonAdapter): T {
    return gson.fromJson(this, T::class.java)
}

/**
 * json转list
 */
inline fun <reified T> String.jsonToList(gson: Gson = defaultGsonAdapter): MutableList<T> {
    return gson.fromJson(this, object : TypeToken<List<T>>() {}.type)
}

/**
 * object转json
 */
fun Any.toJson(gson: Gson = defaultGsonAdapter): String {
    try {
        return gson.toJson(this)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return ""
}

/**
 * 默认转换适配器
 */
val defaultGsonAdapter: Gson =
    GsonBuilder().registerTypeHierarchyAdapter(ByteArray::class.java, ByteArrayToBase64Adapter())
        .setDateFormat("yyyy-MM-dd HH:mm:ss").create()
